import { ITypeEntity } from '@/types/modules/superType/types';
import { getActionTypes } from '@/utils/editor-adapter/editorResource';
import {
  IPublicTypeProjectSchema,
  IPublicTypeRootSchema,
  IPublicTypeUtilsMap,
} from '@alilc/lowcode-types';

/**
 * 根据ActionType生成
 */
export const actionTypeToSchema = async (
  projectSchema: IPublicTypeProjectSchema | null,
  schema: IPublicTypeRootSchema,
  dataType: ITypeEntity,
  isGlobal?: boolean,
  types?: ITypeEntity[],
): Promise<IPublicTypeProjectSchema | IPublicTypeRootSchema> => {
  // 获取此文档下的所有类型
  let actionTypes = types?.filter((_) => _.type === 'action');
  if (!types) {
    actionTypes = await getActionTypes(dataType.fileName, isGlobal);
  }
  const lifeCycles: IPublicTypeRootSchema['lifeCycles'] = {};
  const methods: IPublicTypeRootSchema['methods'] = {};
  mergeLifeCycles(lifeCycles, actionTypes, 'componentDidMount', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'componentWillUnmount', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'componentDidShow', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'componentDidHide', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'onShow', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'onHide', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'onLaunch', isGlobal);
  mergeLifeCycles(lifeCycles, actionTypes, 'componentDidCatch', isGlobal);
  const utils: IPublicTypeUtilsMap = [];
  // @TODO: 问题确定在 上面的时候，把生命周期过滤了

  actionTypes.forEach((action) => {
    methods[action.name] = {
      type: action.code.type,
      value: action.code.value,
    };
    if (isGlobal) {
      utils.push({
        name: action.name,
        type: 'function',
        content: methods[action.name],
      });
    }
  });

  if (isGlobal) {
    return {
      ...projectSchema,
      utils,
    };
  }
  return schema.componentName === 'Component'
    ? {
        ...schema,
        lifeCycles: {},
        methods: {
          ...lifeCycles,
          ...methods,
        },
      }
    : {
        ...schema,
        lifeCycles,
        methods,
      };
};

export const mergeLifeCycles = (
  lifeCycles: IPublicTypeRootSchema['lifeCycles'],
  actionTypes: ITypeEntity[],
  lifeCycleName: string,
  isGlobal?: boolean,
) => {
  const lifeCycleActions = actionTypes.filter((type) => type.lifeCycle === lifeCycleName);
  if (lifeCycleActions.length === 1) {
    const i = actionTypes.findIndex((type) => type.lifeCycle === lifeCycleName);
    if (!isGlobal) actionTypes.splice(i, 1);
    lifeCycles[lifeCycleName] = {
      type: lifeCycleActions[0].code.type,
      value: lifeCycleActions[0].code.value,
    };
  }
  if (lifeCycleActions.length > 1) {
    // @TODO: 待完成多个同名生命周期函数
  }
  return actionTypes;
};
